import base64
import json
import math
import time
import uuid
import random
import sys

import os
os.chdir(os.path.dirname(__file__))
print("1",os.path.dirname(__file__))

import logs
import confhelper
import requests
from playwright.sync_api import Playwright, sync_playwright

import dbmapper
from entity import LinkMonResult, MonLinkBatch, MonLinkVersion, MonLink

# from  base642image import base64_to_img
# from spider_cv import get_notch_location

logger = logs.get_logger('jd')

wiew_size = {"width": 1080, "height": 2240}
linkpath_prefix = confhelper.confdata().get("linkpath_prefix")+"jd/"
work_dir = confhelper.confdata().get("work_dir")
monLinks = []
page_size = 60

logger.info("sys.argv: {}".format(sys.argv))
version = sys.argv[1]

def run(playwright: Playwright, link: MonLink) -> None:
    browser = playwright.firefox.launch(headless=False,slow_mo=3000)
    context = browser.new_context(screen=wiew_size,viewport=wiew_size,storage_state="jd_state.json")
    page = context.new_page()

    i = 0
    url = link.url
    linkId = link.id
    currentPage = link.currentPage + 1

    logger.info("开始遍历 url:{} id:{},当前页：{}，已爬取页：{}".format(url,linkId, currentPage, currentPage - 1))
    page.goto(url)
    page.wait_for_timeout(200)

    if page.locator("text=搜本店").count() == 0:
        logger.error("无效店铺: {}".format(url))
        dbmapper.MonLinkMapper.updateInvalid(MonLink(id=linkId))
        page.close()
        context.close()
        browser.close()
        return

    if page.locator(".J_giftClose.d-close").count()>0:
        logger.info("出现领券框")
        page.locator(".J_giftClose.d-close").click()

    if page.locator("body > div.J_shopCloseModal.d-shop-close > a").count() > 0:
        logger.info("出现公告")
        page.locator("body > div.J_shopCloseModal.d-shop-close > a").click()

    page.wait_for_timeout(200)
    if page.locator('div.d-float-main.J-floatMain > div').count() > 0:
        logger.info("出现广告")
        page.locator("div.d-float-main.J-floatMain > div").click()

    page.locator("text=搜本店").click()

    tempTotal = 0
    if page.locator(".jSearchListArea").count() == 0:
        if page.locator(".jPage").count() > 0:
            tempTotalStr = page.locator('.jPage > em').text_content()
            tempTotal = tempTotalStr.split("共")[1].split("条")[0]
            if int(tempTotal) == 0:
                logger.error("没有商品: {}".format(url))
                dbmapper.MonLinkMapper.updateInvalid(MonLink(id=linkId))
                page.close()
                context.close()
                browser.close()
                return
        else:
            logger.error("没有商品: {}".format(url))
            dbmapper.MonLinkMapper.updateInvalid(MonLink(id=linkId))
            page.close()
            context.close()
            browser.close()
            return

    pageTotal = 0
    if int(tempTotal) == 0:
        pageTotal = page.locator(".jSearchListArea").locator(".jTotal>em").text_content()
    else:
        pageTotal = tempTotal
    pageNum = math.ceil(int(pageTotal)/page_size)
    logger.info("url {} pageTotal {} pagenum: {} ".format(url,pageTotal,pageNum))

    if int(pageTotal) == 0:
        logger.info("没有商品。。。")
        monLinkUpdate = MonLink(version=version, id=linkId, currentPage=currentPage, totalPage=pageNum)
        dbmapper.MonLinkMapper.update_by_id(monLinkUpdate)
        page.close()
        context.close()
        browser.close()
        return

    monLinkBatch=MonLinkBatch(linkId=linkId)
    linkBatchCount = dbmapper.MonLinkBatchMapper.count(monLinkBatch)
    if int(linkBatchCount) > 0:
        dbmapper.MonLinkBatchMapper.update(MonLinkBatch(goodSum=pageTotal,linkId=linkId))
    else:
        monLinkBatchInsert=MonLinkBatch(goodSum=pageTotal,linkId=linkId,status='0',linkUrl=url)
        dbmapper.MonLinkBatchMapper.insert(monLinkBatchInsert)

    for p_num in range(1,currentPage):
        page.locator("text=下一页").click()
        logger.info("点击{}次下一页。。。".format(p_num))
        page.wait_for_timeout(1000)

        while page.locator("text=验证一下，购物无忧").count() > 0:
            logger.info("出现图形验证等待5秒...")
            # passImgCheck(page)
            page.wait_for_timeout(5000)

    page.wait_for_load_state("networkidle")

    logger.info("进度：url :{} linkId :{} 页面进度: {}/{} ".format(url, linkId, currentPage,pageNum))
    pageLinks = page.locator(".jSearchListArea").locator(".jSubObject").all()
    if int(tempTotal) > 0:
        pageLinks = page.locator(".j-module").locator(".jSubObject").all()
    if len(pageLinks) > 0 :
        view_page(currentPage,i,page,pageLinks,url,linkId)

    logger.info("结束遍历 {}".format(url))

    if currentPage >= pageNum:
        monLinkUpdate = MonLink(version=version, id=linkId, currentPage=currentPage, totalPage=pageNum)
        dbmapper.MonLinkMapper.update_by_id(monLinkUpdate)
    else:
        monLinkUpdate = MonLink(version=(int(version) - 1), id=linkId, currentPage=currentPage, totalPage=pageNum)
        dbmapper.MonLinkMapper.update_by_id(monLinkUpdate)
    # Close page
    page.close()
    context.close()
    browser.close()

def view_page(p_num:int,i:int,page,pageLinks,linkUrl,linkId):
    for p in pageLinks:
        i = i + 1
        j = 0
        logger.info("每页进度：{}/{}".format(i, len(pageLinks)))
        try:
            page.wait_for_load_state('networkidle')
            with page.expect_popup(timeout=60000) as popup_info:
                p.first.click()
            page1 = popup_info.value
            page1.wait_for_timeout(1000)

            while page1.locator("text=验证一下，购物无忧").count() >0:
                logger.info("出现图形验证等待5秒...")
                # passImgCheck(page1)
                page1.wait_for_timeout(5000)

            # if page1.locator("text=商品介绍").count() > 0 :
            if page1.locator("text=验证一下，购物无忧").count() == 0:
                pic = linkpath_prefix +str(p_num)+"-"+str(i)+"-"+str(j)+page1.title().replace("*","").replace("/","#").replace(" ","")[0:30]+".png"
                page1.screenshot(path=pic,full_page=True)

                linkMonResult = LinkMonResult(str(uuid.uuid4().int),linkUrl,page1.url,"/profile"+pic.replace(work_dir,""),linkId=linkId)
                count = dbmapper.LinkMonResultMapper.count(linkMonResult)
                if int(count) > 0:
                    linkMonResult.status=0
                    linkMonResult.ocrStr=""
                    dbmapper.LinkMonResultMapper.update(linkMonResult)
                else:
                    dbmapper.LinkMonResultMapper.insert(linkMonResult)

                linkVersion=MonLinkVersion(linkId=linkId, linkUrl=linkUrl, goodUrl=page1.url,version=version)
                lvCount = dbmapper.MonLinkVersionMapper.count(linkVersion);
                if int(lvCount) <= 0:
                    dbmapper.MonLinkVersionMapper.insert(linkVersion)
            else:
                logger.info("出现图形验证进入60秒睡眠")
                #time.sleep(60)
                page1.wait_for_timeout(60000)
            page1.close()
        except Exception as e:
            logger.info("exception {} url:{}".format(i,page1.url))
            logger.exception("exception traceback is:{}".format(e))
            page1.close()

os.chdir(os.path.dirname(__file__))

# def passImgCheck(page):
#     try:
#         if page.locator('.move-img').is_hidden():
#             page.locator('.main-wrap .verifyBtn').click()
#             page.wait_for_timeout(1000)
#
#         smallPath = 'E:\\tmp\\pic\\base64\\jd\\small.png'
#         cpcPath = 'E:\\tmp\\pic\\base64\\jd\\cpc.jpg'
#
#         small = page.get_attribute('xpath=//*[@id="small_img"]', 'src')
#         cpc = page.get_attribute('xpath=//*[@id="cpc_img"]', 'src')
#         base64_to_img(small, smallPath)
#         base64_to_img(cpc, cpcPath)
#
#         move = get_notch_location(smallPath, cpcPath)
#
#         # 移动滑块
#         # 首先咱们的找到要移动的东西吧
#         s = page.wait_for_selector('.move-img', strict=True)
#         # 找到这个元素再当前页面的坐标（这个会返回一个字典里边四个数字）
#         box = s.bounding_box()
#         # 移动鼠标到上边元素的中心（上边四个参数用途来了）
#         page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
#         # 按下鼠标（这个不多说）
#         page.mouse.down()
#         logger.info("按下鼠标。。。")
#         # 这里获取到x坐标中心点位置
#         x = box["x"] + box["width"] / 2
#         # 这个把缺口获取到的长度放到轨迹加工一下得到一个轨迹
#         # tracks = get_track(move)
#         # logger.info("得到一个轨迹。。。")
#         # for track in tracks:
#         #     # 循环鼠标按照轨迹移动
#         #     # strps 是控制单次移动速度的比例是1/10 默认是1 相当于 传入的这个距离不管多远0.1秒钟移动完 越大越慢
#         #     page.mouse.move(x + track, 0, steps=10)
#         #     x += track
#         page.mouse.move(x + move, 0, steps=1)
#         logger.info("移动鼠标。。。")
#         # 移动结束鼠标抬起
#         page.mouse.up()
#         logger.info("抬起鼠标。。。")
#     except Exception as e:
#         logger.exception("exception traceback is:{}".format(e))


#有的检测移动速度的 如果匀速移动会被识别出来，来个简单点的 渐进
def get_track(distance):  # distance为传入的总距离
    # 移动轨迹
    track = []
    # 当前位移
    current = 0
    # 减速阈值
    mid = distance * 4 / 5
    # 计算间隔
    t = 0.2
    # 初速度
    v = 1
    while current < distance:
        if current < mid:
            # 加速度为2
            a = 4
        else:
            # 加速度为-2
            a = -3
        v0 = v
        # 当前速度
        v = v0 + a * t
        # 移动距离
        move = v0 * t + 1 / 2 * a * t * t
        # 当前位移
        current += move
        # 加入轨迹
        track.append(round(move))
    return track


# 通过db加载url
monLink = dbmapper.MonLinkMapper.list_by_typea('jd', version)
if len(monLink) > 0:
    monLinks = monLink

logger.info("待监测的url %s",[(link.id,link.url) for link in monLinks])
currentI = 0
if len(monLinks) > 0:
    for link in monLinks:
        currentI = currentI + 1
        logger.info("整体进度：{}/{}".format(currentI, len(monLinks)))
        with sync_playwright() as playwright:
            run(playwright, link)
